import { HTTP } from './modelApi/httprequest.js'
import { url } from './modelApi/url_config.js'
import TIM from 'tim-wx-sdk';
import COS from "cos-wx-sdk-v5";
// import { SDKAPPID, genTestUserSig } from './utils/GenerateTestUserSig'
const HttpFunc = new HTTP()
App({
    globalData: {
        statusBarHeight: "",
        navHeight: "",
        navTop: "",
        windowHeight: "",
        wxTIM: null,
        wxSdk: null,
        TIM: null,
        conversationList: [],
        TIMmessageList: [],
        isShow: true
    },
    onLaunch: function () {
        wx.hideTabBar();
        this.getMenu();
        this.ifLogin();
        this.setSty();
        const tim = TIM.create({
            SDKAppID: 1400343726
        })
        tim.setLogLevel(1)
        this.globalData.wxTIM = tim
        tim.registerPlugin({'cos-wx-sdk': COS})
        this.globalData.TIM = TIM
        // 侧监听
        tim.on(TIM.EVENT.SDK_READY,  (event) => {
            // 修改个人标配资料
            let promise5 = tim.updateMyProfile({
                nick: wx.getStorageSync('nickName'),
                avatar: wx.getStorageSync('avatar')
            });
            promise5.then(function(imResponse) {
                console.log(imResponse.data,'更新资料成功'); // 更新资料成功
            }).catch(function(imError) {
                console.warn('updateMyProfile error:', imError); // 更新资料失败的相关信息
            });
        });
        wx.getStorageSync('userId') && this.getimLoad()
    },
    getimLoad(callback) {
        this.ajax(url.getUserSig, {userId: wx.getStorageSync('userId')}, 'get').then(res => {
            if (+res.code === 0) {
                this.globalData.wxTIM.login({
                    userID: wx.getStorageSync('userId').toString(),
                    userSig:  res.data
                }).then((imResponse) => {
                    console.log(imResponse,"IM登录成功");
                    callback&&callback()
                }).catch(() => {})
                
            }
        })
    },
    // 判断是否需要重新登录拿到accesstoken
    ifLogin(callback) {
        const accessToken = wx.getStorageSync('accessToken')
        if (!accessToken) {
            wx.login({
                success: res => {
                    this.get_User_Info(res.code, callback)
                }
            })
        }
    },
    get_User_Info(code,callback) {
        wx.getUserInfo({
            success: (e) => {
                const param = {
                    code: code,
                    encryptedData: e.encryptedData,
                    iv: e.iv,
                    promoterId: wx.getStorageSync('shareUserId') ? wx.getStorageSync('shareUserId') : ''
                }
                this.ajax(url.onload, param, 'post').then(res => {
                    const info = res.data.userInfo;
                    wx.setStorageSync('accessToken', res.data.token);
                    // isMember 、isAnchor 、isStore 的三种身份
                    wx.setStorageSync('isMember', info.isMember);
                    wx.setStorageSync('isAnchor', info.isAnchor); 
                    wx.setStorageSync('isStore', info.isStore); 
                    wx.setStorageSync('userId', info.userId);
                    wx.setStorageSync('nickName', info.nickName);
                    wx.setStorageSync('openId', info.openId);
                    wx.setStorageSync('avatar', info.avatar);
                    this.getimLoad();
                    callback && callback();
                })
            }
        })
    },
    ajax(url, data = {}, method = 'GET') {
        return new Promise((resolve, reject) => {
            HttpFunc._request(url, resolve, reject, data, method)
        })
    },
    // 减法精度计算
    sub(arg1, arg2) {
        var r1, r2, m, n;
        try {
            r1 = arg1.toString().split(".")[1].length;
        }
        catch (e) {
            r1 = 0;
        }
        try {
            r2 = arg2.toString().split(".")[1].length;
        }
        catch (e) {
            r2 = 0;
        }
        m = Math.pow(10, Math.max(r1, r2));
        //动态控制精度长度
        n = (r1 >= r2) ? r1 : r2;
        return ((arg1 * m - arg2 * m) / m).toFixed(n);
    },
    setSty() {
        var logs = wx.getStorageSync('logs') || []
        logs.unshift(Date.now())
        let menuButtonObject = wx.getMenuButtonBoundingClientRect();
        wx.getSystemInfo({
            success: res => {
                let statusBarHeight = res.statusBarHeight,
                    navTop = menuButtonObject.top, //胶囊按钮与顶部的距离
                    navHeight = statusBarHeight + menuButtonObject.height + (menuButtonObject.top - statusBarHeight) * 2; //导航高度
                this.globalData.navHeight = navHeight;
                this.globalData.navTop = navTop;
                this.globalData.windowHeight = res.windowHeight;
            }
        })
    },
    getMenu() {
        this.ajax(url.menuList, {versionNo:'1'}, 'get').then(res => {
            if (res.data.isShow) {
                this.globalData.isShow = true
                wx.showTabBar();
            } else {
                this.globalData.isShow = false;
            }
        })
    }
})